# -*- coding: utf-8 -*-
"""
需求管理服务模块
实现需求提交、处理和管理功能

主要功能:
- 需求CRUD操作
- 需求状态管理
- 需求分析和处理
- 需求统计和报告
"""

import json
import uuid
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime, timezone
import logging
from dataclasses import dataclass, asdict
from enum import Enum

from .template_service import TemplateService

# 配置日志
logger = logging.getLogger(__name__)


class RequirementStatus(Enum):
    """需求状态枚举"""
    PENDING = "pending"  # 待处理
    PROCESSING = "processing"  # 处理中
    COMPLETED = "completed"  # 已完成
    FAILED = "failed"  # 处理失败
    CANCELLED = "cancelled"  # 已取消


class RequirementPriority(Enum):
    """需求优先级枚举"""
    LOW = "low"  # 低优先级
    MEDIUM = "medium"  # 中等优先级
    HIGH = "high"  # 高优先级
    URGENT = "urgent"  # 紧急


# 移除了复杂的需求分析功能，保持简单的数据结构


# 内存存储
_requirement_storage = {}
_requirement_counter = 0

class RequirementService:
    """需求管理服务类"""
    
    def __init__(self):
        self.template_service = TemplateService()
        
        # 需求分析配置
        self.complexity_keywords = {
            'high': ['复杂', '多渠道', '整合', '全面', '深度', '定制'],
            'medium': ['详细', '专业', '系统', '完整', '优化'],
            'low': ['简单', '基础', '快速', '标准', '常规']
        }
        
        # 初始化默认数据
        self._init_default_requirements()
    
    def _init_default_requirements(self):
        """初始化默认需求数据"""
        global _requirement_storage, _requirement_counter
        
        if not _requirement_storage:
            # 添加示例需求
            sample_requirement = {
                'id': 'req_001',
                'template_id': 'tpl_001',
                'core_goal': '提升品牌知名度',
                'target_audience': '25-35岁都市白领',
                'budget_per_person': 100,
                'focus_point': '产品功能优势',
                'gift_preference': '实用性礼品',
                'specific_product': '智能手表',
                'customer_preference': '简约设计，功能实用',
                'customer_pain_point': '市面产品功能复杂，操作不便',
                'status': RequirementStatus.COMPLETED.value,
                'created_at': datetime.now(timezone.utc),
                'updated_at': datetime.now(timezone.utc)
            }
            _requirement_storage['req_001'] = sample_requirement
            _requirement_counter = 1
    
    def submit_requirement(
        self,
        template_id: str,
        core_goal: str,
        target_audience: str,
        budget_per_person: float,
        focus_point: str,
        gift_preference: str = '',
        specific_product: str = '',
        customer_preference: str = '',
        customer_pain_point: str = ''
    ) -> Dict[str, Any]:
        """
        提交营销需求
        
        Args:
            template_id: 模板ID
            core_goal: 核心目标
            target_audience: 目标受众
            budget_per_person: 人均预算
            focus_point: 重点关注
            gift_preference: 礼品偏好
            specific_product: 具体产品
            customer_preference: 客户偏好
            customer_pain_point: 客户痛点
            
        Returns:
            Dict[str, Any]: 包含需求ID和生成的prompt
        """
        try:
            global _requirement_storage, _requirement_counter
            
            # 生成需求ID
            _requirement_counter += 1
            requirement_id = f"req_{_requirement_counter:03d}"
            
            # 创建需求数据
            requirement_data = {
                'id': requirement_id,
                'template_id': template_id,
                'core_goal': core_goal,
                'target_audience': target_audience,
                'budget_per_person': budget_per_person,
                'focus_point': focus_point,
                'gift_preference': gift_preference,
                'specific_product': specific_product,
                'customer_preference': customer_preference,
                'customer_pain_point': customer_pain_point,
                'status': RequirementStatus.PENDING.value,
                'created_at': datetime.now(timezone.utc),
                'updated_at': datetime.now(timezone.utc)
            }
            
            # 存储需求
            _requirement_storage[requirement_id] = requirement_data
            
            # 生成营销方案prompt
            prompt = self._generate_marketing_prompt(requirement_data)
            
            logger.info(f"成功提交需求: {requirement_id}")
            
            return {
                'requirement_id': requirement_id,
                'prompt': prompt
            }
            
        except Exception as e:
            logger.error(f"提交需求失败: {e}")
            raise ValueError(f"提交需求失败: {str(e)}")
    
    def _generate_marketing_prompt(self, requirement_data: Dict[str, Any]) -> str:
        """
        生成营销方案prompt
        
        Args:
            requirement_data: 需求数据
            
        Returns:
            str: 生成的prompt
        """
        prompt = f"""
请为以下营销需求生成一个详细的营销方案：

核心目标：{requirement_data['core_goal']}
目标受众：{requirement_data['target_audience']}
人均预算：{requirement_data['budget_per_person']}元
重点关注：{requirement_data['focus_point']}
客户偏好：{requirement_data['customer_preference']}
客户痛点：{requirement_data['customer_pain_point']}
"""
        
        if requirement_data.get('gift_preference'):
            prompt += f"\n礼品偏好：{requirement_data['gift_preference']}"
        
        if requirement_data.get('specific_product'):
            prompt += f"\n具体产品：{requirement_data['specific_product']}"
        
        prompt += """

请生成包含以下内容的营销方案：
1. 营销策略概述
2. 目标受众分析
3. 营销渠道建议
4. 预算分配方案
5. 执行时间规划
6. 效果评估指标
7. 风险控制措施

请确保方案具有可操作性和针对性。
"""
        
        return prompt.strip()
    
    def get_requirement(self, requirement_id: str) -> Optional[Dict[str, Any]]:
        """
        根据需求ID获取需求信息
        
        Args:
            requirement_id: 需求ID
            
        Returns:
            Dict[str, Any]: 需求信息，如果不存在则返回None
        """
        global _requirement_storage
        
        try:
            requirement = _requirement_storage.get(requirement_id)
            if requirement:
                logger.info(f"成功获取需求信息: {requirement_id}")
                return requirement
            else:
                logger.warning(f"需求不存在: {requirement_id}")
                return None
                
        except Exception as e:
            logger.error(f"获取需求信息失败: {e}")
            return None
    
    # 移除了复杂的需求管理方法，只保留核心的提交功能
    # 符合文档要求的简单功能设计

# 全局服务实例
requirement_service = RequirementService()


def get_requirement_service() -> RequirementService:
    """
    获取需求服务实例
    
    Returns:
        RequirementService: 需求服务实例
    """
    return requirement_service


# 便利函数
def submit_marketing_requirement(
    user_id: str,
    title: str,
    description: str,
    requirement_type: str = 'marketing_plan',
    priority: str = RequirementPriority.MEDIUM.value,
    target_audience: str = None,
    budget_range: str = None,
    timeline: str = None,
    additional_info: dict = None
) -> tuple:
    """
    提交营销需求的便利函数
    
    Args:
        user_id: 用户ID
        title: 需求标题
        description: 需求描述
        requirement_type: 需求类型
        priority: 优先级
        target_audience: 目标受众
        budget_range: 预算范围
        timeline: 时间线
        additional_info: 额外信息
        
    Returns:
        tuple: (需求ID, 营销提示)
    """
    return requirement_service.submit_requirement(
        user_id=user_id,
        title=title,
        description=description,
        requirement_type=requirement_type,
        priority=priority,
        target_audience=target_audience,
        budget_range=budget_range,
        timeline=timeline,
        additional_info=additional_info or {}
    )